<?php
/**
 * 发送短信接口
 *
 * Author: Youzi
 * Date: 13-3-10
 * Time: 下午12:18
 * To change this template use File | Settings | File Templates.
 */
define('MKEY', '3b9c261e2c580f8a4d7d62d659f5c733');
class MessageController extends Controller
{
    public function sendAction()
    {
        $key     = $_REQUEST['key'];
        if (!$key && $key != MKEY) {
            return false;
        }

        $tel     = $_REQUEST['tel'];
        $content = $_REQUEST['content'];
        $tel = $this->_checkTel($tel);
        if (!$tel) {
            return ;
        }
        file_put_contents('LogMessage.log', '['.date('m-d H:i:s',time()).']'.$content.'---'.$tel."\r\n",FILE_APPEND);

        $flag = 0;
        $argv = array(
            'sn'        => 'DXX-WSS-010-03286',
            'pwd'       => strtoupper(md5('DXX-WSS-010-03286'.'a-e(c7-4')),
            'mobile'    => $tel,
            'content'   => iconv('utf-8', 'gb2312', $content),
            'ext'       => '',
            'stime'     => '',
            'rrid'      => ''
        );

        $params = '';
        foreach ($argv as $key=>$value) {
            if ($flag!=0) {
                $params .= "&";
                $flag = 1;
            }
            $params.= $key."="; $params.= urlencode($value);
            $flag = 1;
        }
        $length = strlen($params);
        $fp     = fsockopen("sdk2.zucp.net",8060,$errno,$errstr,10) or exit($errstr."--->".$errno);

        $header  = "POST /webservice.asmx/mt HTTP/1.1\r\n";
        $header .= "Host:sdk2.zucp.net\r\n";
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: ".$length."\r\n";
        $header .= "Connection: Close\r\n\r\n";
        $header .= $params."\r\n";

        fputs($fp, $header);
        $inheader = 1;
        while (!feof($fp)) {
            $line = fgets($fp,1024);
            if ($inheader && ($line == "\n" || $line == "\r\n")) {
                $inheader = 0;
            }
            if ($inheader == 0) {}
        }
        $line   = str_replace("<string xmlns=\"http://tempuri.org/\">","",$line);
        $line   = str_replace("</string>","",$line);
        $result = explode("-",$line);

        return count($result) > 1 ? false : true;
    }
    /**
     * 验证电话号码是否合法
     *
     * @param  string   $tel
     * @return string
     */
    private function _checkTel($tel)
    {
        if (!$tel) {
            return ;
        }
        $tel     = explode(',', $tel);
        $pattern = "/^(13[0-9]|15[0|1|2|3|5|6|7|8|9]|18[0|5|6|7|8|9])\d{8}$/";
        $source  = array();
        foreach ($tel as $value) {
            preg_match($pattern, $value,$match);
            if ($match && is_array($match)){
                $source[] = $match[0];
            }
        }
        $source = array_unique($source);
        return implode(',', $source);
    }
}
